/*
 * =====================================================================================
 *
 *       Filename:  main.c
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2019年09月18日 11时20分15秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  YOUR NAME (), 
 *   Organization:  
 *
 * =====================================================================================
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <net/if_arp.h>
#include <netinet/in.h>
#include <arpa/inet.h>

void Usage(const char *program)
{
    printf("%s query eth ip\n", program);
}

int arp_query(const char *eth, const char *ip)
{
    printf("%s: %s %s\n", __func__, eth, ip);
    int fd = socket(AF_INET, SOCK_DGRAM, 0);
    if(fd < 0) {
        perror("socket()");
        return -1;
    }

    struct arpreq arp;
    memset(&arp, 0, sizeof(arp));
    ((struct sockaddr_in *)&(arp.arp_pa))->sin_family = AF_INET;
    ((struct sockaddr_in *)&(arp.arp_pa))->sin_addr.s_addr = inet_addr(ip);
    strncpy(arp.arp_dev, eth, sizeof(arp.arp_dev));
    if(ioctl(fd, SIOCGARP, &arp) < 0) {
        perror("ioctl()");
    }
    else {
        char *hw = (char *)(&(arp.arp_ha.sa_data));
        printf("%s HardWare Address: %02X:%02X:%02X:%02X:%02X:%02X\n", 
                ip, hw[0]&0xff, hw[1]&0xff, hw[2]&0xff, hw[3]&0xff, hw[4]&0xff, hw[5]&0xff);
    }
    close(fd);
    return 0;
}

int main(int argc, char **argv)
{
    if(argc <= 3) {
        Usage(argv[0]);
        return 0;
    }

    if(0 == strcmp(argv[1], "query")) {
        arp_query(argv[2], argv[3]);
    }
    else if(0 == strcmp(argv[1], "del")) {
        //arp_del();
    }
    else if(0 == strcmp(argv[1], "add")) {
        //arp_add();
    }
    else {
        printf("Unsupported method: %s\n", argv[1]);
    }

    return 0;
}

